#!/bin/sh

MAVEN_VERSION=3.8.5
MAVEN_NAME=apache-maven-$MAVEN_VERSION
MY_SOFTS=/usr/local/mysofts
FILE_NAME=$MAVEN_NAME-bin.tar.gz
# 判断maven包是否存在，不存在那么从网络下载
echo $FILE_NAME
if [ -f $FILE_NAME ];then
    echo "maven软件包不需要下载"
else
   wget --no-check-certificate 'https://dlcdn.apache.org/maven/maven-3/3.8.5/binaries/apache-maven-3.8.5-bin.tar.gz'
fi

# 判断解压文件是否存在，不存在就解压
if [ ! -d $MAVEN_NAME ];then
   echo 'maven未解压，直接解压'
   tar -zxvf $FILE_NAME
else
    echo "maven已经解压完成,先删除解压文件目录，再解压"
    rm -rf $MAVEN_NAME
    tar -zxvf $FILE_NAME
fi

# 判断软件存放目录是否存在，如果存在先删除再创建
soft_maven_path=$MY_SOFTS/maven3
if [ ! -d $soft_maven_path ];then
   echo 'maven存放目录/user/local/mysofts/maven3不存在,创建目录'
   mkdir -p $soft_maven_path
else
    echo "maven存放软件目录存在,先删除，再创建"
    rm -rf $soft_maven_path
    mkdir -p $soft_maven_path
fi

echo '拷贝maven的当前目录到 /usr/local/mysofts/mavens目录下'
mv $MAVEN_NAME $soft_maven_path

# a表示添加
echo "修改数据源....."
nvm=/usr/local/mysofts/maven3/apache-maven-3.8.5
num=$(sed -n  '/<mirrors>/=' $nvm/conf/settings.xml)
sed -i "`expr $num`a<mirror>" $nvm/conf/settings.xml
sed -i "`expr $num + 1`a<id>aliyunmaven<\/id>" $nvm/conf/settings.xml
sed -i "`expr $num + 2`a<mirrorOf>*<\/mirrorOf>" $nvm/conf/settings.xml
sed -i "`expr $num + 3`a<name>阿里云公共仓库<\/name>" $nvm/conf/settings.xml
sed -i "`expr $num + 4`a<url>https://maven.aliyun.com/repository/public<\/url>" $nvm/conf/settings.xml
sed -i "`expr $num + 5`a<\/mirror>" $nvm/conf/settings.xml


# sed -i模式是在原来的基础上进行修改
# set "2/d" /etc/profile是删除第二行
# sed "/JAVA_HOME/d" /etc/profile是删除文件中的匹配JAVA_HOME的行删除
sed -i '/M2_HOME/d' /etc/profile

# 获取export PATH=$PATH下的内容,使用字符串的截取=右边的字符串
content=$(grep 'export PATH' /etc/profile)
path='export PATH='${content#*=}':$M2_HOME/bin'
echo "获取到的PATH的content是："$content
echo "需要设置到环境变量的path是："$path
# 删除PATH
sed -i '/export PATH/d' /etc/profile

echo "配置环境变量"
cat >> /etc/profile <<"EOF"
export M2_HOME=/usr/local/mysofts/maven3/apache-maven-3.8.5
EOF

# 最后一行添加PATH
#这是在最后一行行后添加字符串
echo $path >>/etc/profile

source /etc/profile
echo '验证是否安装OK'
mvn -v
